﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SimpleNetTemplate
{
	#region << 版 本 注 释 >>
	/*----------------------------------------------------------------
	 * 版权所有 (c) 2025   保留所有权利。
	 * CLR版本：4.0.30319.42000
	 * 公司名称：
	 * 命名空间：SimpleNetTemplate
	 * 唯一标识：95377591-b933-453b-a572-5862ac861c27
	 * 文件名：Connection
	 * 
	 * 创建者：dongming
	 * 电子邮箱：15688277399@163.com
	 * 创建时间：2025/6/13 11:52:40
	 * 版本：V1.0.0
	 * 描述：
	 *----------------------------------------------------------------*/
	#endregion << 版 本 注 释 >>
	public class TcpConnection
	{
		private int _port;


		private string _host;

		TcpClient _client;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="prot"></param>
		/// <param name="host"></param>
		public TcpConnection(string host, int port)
		{
			_port = port;
			_host = host;

			//拔了网线测试
			_client = new TcpClient();
		}

		/// <summary>
		/// 
		/// </summary>
		public void Connect()
		{
			IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(_host), _port);
			_client.Connect(ipPoint);
		}

		/// <summary>
		/// 
		/// </summary>
		public bool Connected
		{
			get
			{
				if (_client == null)
				{
					return false;
				}
				return _client.Connected;
			}
			private set { }
		}

		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="msg"></param>
		/// <returns></returns>
		public string Send(string msg)
		{
			if (!_client.Connected)
			{
				Connect();
			}
			var networkStream = _client.GetStream();
			var buffer = Encoding.UTF8.GetBytes(msg);
			//buffer[8] = 0;
			//buffer[9] = 0;
			//buffer[10] = 0;
			//buffer[11] = 1;

			networkStream.Write(buffer, 0, buffer.Length);
			networkStream.ReadTimeout = 10000;
			var readBuffer = new byte[1024 * 1024 * 10];//10M
			var len = networkStream.Read(readBuffer, 0, readBuffer.Length);
			var result = Encoding.UTF8.GetString(readBuffer, 0, len);
			var lines = result.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
			//foreach (var line in lines)
			//{
			//	if (line.StartsWith("A01"))
			//	{
			//		var fields = line.Split(',');
			//		string value = fields[2].Trim();
			//		break;
			//	}
			//}
			//networkStream.Close(3000);
			return result;
		}
	}
}